/*
 * ThreadHandler.cpp
 *
 *  Created on: 2012-11-30
 *      Author: yangentao@gmail.com
 */

#include <windowsx.h>
#include <process.h>
#include "Handler.h"
#include "win32.h"
#include "Log.h"

using namespace std;

namespace yet {

Handler::Handler() {
	active = false;
}
Handler::~Handler() {
	assert(!isActive());
}
boost::signals2::connection Handler::addHandler(const MsgHandler& msgHandler) {
	AutoLock al(this);
	return sig.connect(msgHandler);
}

void Handler::peekAndProcess() {
	AutoLock al(messages);
	if (messages.isEmpty()) {
		return;
	}
	Message msg = messages.pop_front();
	al.unLock();
	if (msg.isQuit()) {
		quit();
	} else {
		if (OnMessage) {
			OnMessage(msg);
		}
		if (!sig.empty()) {
			sig(msg);
		}
	}
}

void Handler::post(Message msg, bool front) {
	if (front) {
		messages.push_front(msg);
	} else {
		messages.push_back(msg);
	}
	if (isActive()) {
		notify();
	}
}
void Handler::postFront(Message msg) {
	post(msg, true);
}
void Handler::postQuitMessage() {
	Message q;
	q.quit = true;
	post(q);
}
bool Handler::start() {
	assert(!isActive());
	AutoLock al(this);
	active = onStart();
	return active;
}
//shutdown immediatly
void Handler::quit() {
	AutoLock al(this);
	if (isActive()) {
		active = false;
		onQuit();
		if (OnCancel) {
			AutoLock al(messages);
			while (!messages.isEmpty()) {
				OnCancel(messages.pop_back());
			}
		}
	}
}
bool Handler::isActive() {
	AutoLock al(this);
	return active;
}

DWORD Handler::waitFinish() {
	return 0;
}

}
